package com.javabi.unix.util;

public class Numbers {

	public static int parseFirstInt(String text) {
		text = parseDigits(text);
		return Integer.parseInt(text);
	}

	public static long parseFirstLong(String text) {
		text = parseDigits(text);
		return Long.parseLong(text);
	}

	private static String parseDigits(String text) {
		int start = -1;
		int end = text.length();
		for (int i = 0; i < text.length(); i++) {
			char c = text.charAt(i);
			if (start == -1) {
				if (Character.isDigit(c)) {
					start = i;
					continue;
				}
			} else {
				if (!Character.isDigit(c)) {
					end = i;
					break;
				}
			}
		}
		if (start == -1 || start == end) {
			throw new IllegalArgumentException("no digits found in string: '" + text + "'");
		}
		return text.substring(start, end);
	}

}
